package com.ssh.repository.impl;

import com.ssh.entity.User;
import com.ssh.repository.UserRepository;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;


@Repository
public class UserRepositoryImpl implements UserRepository {
    @Autowired
    private SessionFactory sessionFactory;

    private Session getCurrentSession() {
        return sessionFactory.openSession();
    }


    @Override
    public User getUserByAccount(User user) {
        Query q = getCurrentSession().createSQLQuery("select * from tally_user where account=? limit 1").addEntity(User.class);
        q.setParameter(0, user.getAccount());
        List<User> list = q.list();
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    @Override
    public int updateByHql(User user) {
        String hql = "UPDATE User set token = :token "  +
                "WHERE id = :id";
        Query query = getCurrentSession().createQuery(hql);
        query.setParameter("token", user.getToken());
        query.setParameter("id", user.getId());
        int result = query.executeUpdate();
        return result;
    }

    @Override
    public User load(Long id) {
        return null;
    }

    @Override
    public User get(Long id) {
        return (User) getCurrentSession().get(User.class, id);
    }

    @Override
    public List<User> findAll() {
        return null;
    }

    @Override
    public void persist(User entity) {

    }

    @Override
    public Long save(User entity) {
        return (Long) getCurrentSession().save(entity);
    }

    @Override
    public void saveOrUpdate(User entity) {
        getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public void update(User entity) {
        Session session = sessionFactory.openSession();
        session.beginTransaction();
        getCurrentSession().update(entity);
        session.getTransaction().commit();
    }

    @Override
    public void delete(Long id) {

    }

    @Override
    public void flush() {

    }
}
